#include "cfg.h"
#include "make_log.h"
#include <malloc.h>
#include "cJSON.h"
#include <string.h>

//配置路径
#define CFG_PATH "/home/ubuntu/main/conf/cfg.json"

int get_cfg_value(const char* profile, char* title, char* key, char* value)
{
    int ret = 0;
    char* buf = NULL;
    FILE* fp = NULL;

    if(profile == NULL || title == NULL || key == NULL || value == NULL)
    {
        return -1;
    }

    //只读方式打开文件
    fp = fopen(profile, "rb");
    if(fp == NULL)
    {
        perror("fopen");
        LOG("fopen err\n");
        ret = -1;
        goto END;
    }

    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    buf = (char*)calloc(1, size+1);
    if(buf == NULL)
    {
        perror("calloc");
        LOG("calloc err\n");
        ret = -1;
        goto END;
    }

    //读取文件内容
    fread(buf, 1, size, fp);

    //解析一个json字符串为cJSON对象
    cJSON* root = cJSON_Parse(buf);
    if(root == NULL)
    {
        LOG("root err\n");
        ret = -1;
        goto END;
    }

    //返回指定字符串对应的json对象
    cJSON* father = cJSON_GetObjectItem(root, title);
    if(NULL == father)
    {
        cJSON_Delete(root);
        LOG("father err\n");
        ret = -1;
        goto END;
    }

    cJSON* son = cJSON_GetObjectItem(father, key);
    if(NULL == son)
    {
        cJSON_Delete(root);
        LOG("son err\n");
        ret = -1;
        goto END;
    }

    strcpy(value, son->valuestring);
    cJSON_Delete(root);
END:
    if(fp != NULL)
    {
        fclose(fp);
    }

    if(buf != NULL)
    {
        free(buf);
    }

    return ret;
}

int get_mysql_info(char* mysql_user, char* mysql_pwd, char* mysql_db)
{
    if(-1 == get_cfg_value(CFG_PATH, "mysql", "user", mysql_user))
    {
        LOG("mysql_user err\n");
        return -1;
    }

    if(-1 == get_cfg_value(CFG_PATH, "mysql", "password", mysql_pwd))
    {
        LOG("mysql_pwd err\n");
        return -1;
    }

    if(-1 == get_cfg_value(CFG_PATH, "mysql", "database", mysql_db))
    {
        LOG("mysql_db err\n");
        return -1;
    }

    return 0;
}